package com.rpj.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.rpj.dao.BookDao;
import com.rpj.entity.Book;
import com.rpj.entity.BookDto;
import com.rpj.entity.StuDto;
import com.rpj.entity.StuEntity;
import com.rpj.service.BookService;
@Service
public class BookImpl implements BookService {
	@Autowired
	 BookDao bookdao;
	public List<Book> query(){
		List<Book> query = bookdao.query();
		return query;
	}
	@Override
	public int updateBook(String bookname, String bookauthor, String bookpress, String booknum, String bookcate,
			String bookmessage, String bookprice, String bookaddress, String onlinenum, String borrownum,
			String bookid) {
		// TODO Auto-generated method stub
		return bookdao.updateBook(bookname, bookauthor, bookpress, booknum, bookcate, bookmessage, bookprice, bookaddress, onlinenum, borrownum, bookid);
	}
	@Override
	public Book save(Book b) {
		// TODO Auto-generated method stub
		return bookdao.save(b);
	}
	@Override
	public Page<Book> queryByCondition(BookDto dto, Pageable pageable) {
		Specification<Book> spec = getspec(dto);
		return bookdao.findAll(spec, pageable);
	}
	@Override
	public List<String> bookpress() {
		// TODO Auto-generated method stub
		return bookdao.bookpress();
	}
	public Specification<Book> getspec(final BookDto dto){
		return new Specification<Book>() {

			public javax.persistence.criteria.Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				//创建sql表达式
				javax.persistence.criteria.Predicate p = criteriaBuilder.conjunction();
				//声明表达式集合
				List<Expression<Boolean>> list = p.getExpressions();
				if(dto.getBookname()!=""&&dto.getBookname()!=null) {
					list.add(criteriaBuilder.like(root.get("bookname").as(String.class), "%"+dto.getBookname()+"%"));
				}
				if(dto.getBookauthor()!=""&&dto.getBookauthor()!=null) {
					list.add(criteriaBuilder.like(root.get("bookauthor").as(String.class), "%"+dto.getBookauthor()+"%"));
				}
				if(dto.getBookpress()!=""&&dto.getBookpress()!=null) {
					list.add(criteriaBuilder.like(root.get("bookpress").as(String.class), "%"+dto.getBookpress()+"%"));
				}
				
				return p;
			}
		};
	}
}
